clear

% srcFile = fullfile(matlabroot,'toolbox','matlab','demos','example.h5');
% copyfile(srcFile,'myfile.h5');
% fileattrib('myfile.h5','+w');
% fid = H5F.open('myfile.h5','H5F_ACC_RDWR','H5P_DEFAULT');
% dset_id = H5D.open(fid,'/g4/time');
% H5D.set_extent(dset_id,5);
% H5D.close(dset_id);
% H5F.close(fid);

p = '\\PC0647\d\data\2014\02\07\12_21_42\run_0.h5';
fullDataPath = '/dataAnalysis/yyyy';


% H5D.set_extent(dset_id,[5 5]);


value = rand(2,1);
dsize = fliplr(size(value));

try
    fid = H5F.open(p,'H5F_ACC_RDWR','H5P_DEFAULT');
    dset_id = H5D.open(fid,fullDataPath,'H5P_DEFAULT');
%     space = H5D.get_space(dset_id);
    H5D.set_extent(dset_id,dsize);
    h5write(p,fullDataPath,value)
catch err
    if strcmp(err.identifier,'MATLAB:imagesci:h5read:datasetDoesNotExist') || ...
            strcmp(err.identifier,'MATLAB:imagesci:hdf5lib:libraryError')
        % Variable doesn't exist, make it:
        h5create(p,fullDataPath,[inf inf],'ChunkSize',[1 1])
        h5write(p,fullDataPath,value)
    else
        rethrow(err);
    end
end


h5disp(p)

% fileattrib(p,'+w');
% fid = H5F.open(p,'H5F_ACC_RDWR','H5P_DEFAULT');
% dset_id = H5D.open(fid,fullDataPath,'H5P_DEFAULT');
% space = H5D.get_space (dset_id);
% H5D.set_extent(dset_id,[5 5]);
% H5D.close(dset_id);
% H5F.close(fid);
% 
% h5disp(p)

% To create re-sizable datasets: create space with Inf size with correct
% number of dimensions, set_extent to be size of data, then write data. 


% try
%     x = h5read(hdfFilePath,fullDataPath);
%     if size(x) == size(value)
%         h5write(hdfFilePath,fullDataPath,value)
%     else
%         warning('Data sizes non-commensurate, not saving (the new data size doesn''t match the old data size, so h5write() can''t overwrite the data).')
%         % HDF files need the new data to have the same size as the original
%         % data, I haven't worked out how to resize them yet.
%     end
% catch err
%     if strcmp(err.identifier,'MATLAB:imagesci:h5read:datasetDoesNotExist')
%         % Variable doesn't exist, make it:
%         h5create(hdfFilePath,fullDataPath,size(value))
%         h5write(hdfFilePath,fullDataPath,value)
%     else
%         rethrow(err);
%     end
% end